# -*- coding:utf-8 -*-
import os
import datetime

from flask import jsonify
from flask import g
from flask import redirect
from flask import render_template
from flask import request
from flask import url_for
from flask import flash
from flask import session
from flask_login import current_user

from app import db
from app.views.safe import safe
from app.models.log import StaffLog, UserLog
from app.models.account import Staff, DefPassword, User, Freeze

from app.tools.permission import permission
from app.tools.log import log


def random_string():
    import uuid
    return str(uuid.uuid4())


xfrs_dict = {
    '599be19c-faeb-4284-9083-14e39b8d40df': 0
}


def signin_required():
    if not current_user.is_authenticated:
        return redirect(url_for('auth.login'))


safe.before_request(signin_required)


@safe.before_request
@permission(['manage', 'admin', 'super', 'hr'])
def check_permission():
    g.kw = {}
    return


@safe.route('/operation_record', methods=['GET'])
def operation_record():
    xfrs = random_string()
    xfrs_dict.update({xfrs: 0})
    return render_template('safe/operation_record.html',
                           xfrs=xfrs)


@safe.route('/freeze/<id>', methods=['POST'])
def freeze(id):
    form = request.get_json()
    reason = form.get('reason', '')
    id = form.get('id')
    xfrs = form.get('xfrs')
    if xfrs in xfrs_dict and id and reason:
        xfrs_dict.pop(xfrs)
        l = StaffLog.query.get_or_404(id)
        staff_number = l.staff_number
        s = Staff.query.filter_by(staff_number=staff_number).first()
        # s.disable_reason = reason
        # s.account_state = u'禁用'
        sid = session['sid']
        name = session['name']
        s.account_state = 1
        s.save()
        data = dict(
            number=staff_number,
            user_id=s.id,
            reason=reason,
            freeze_id=sid,
            freeze_name=name,
            freeze_time=datetime.datetime.now(),
        )
        f = Freeze(**data)
        db.session.add(f)
        db.session.commit()
        log(u'冻结账户:{}'.format(staff_number))
        return jsonify(dict(
            message=u'冻结成功！',
            success=True
        ))
    return jsonify(dict(
        success=False,
        message=u'页面已过期，请刷新页面！'
    ))


@safe.route('/unfreeze/<id>', methods=['POST'])
def unfreeze(id):
    form = request.get_json()
    xfrs = form.get('xfrs')
    id = form.get('id')
    if xfrs in xfrs_dict:
        xfrs_dict.pop(xfrs)
        l = StaffLog.query.get_or_404(id)
        staff_number = l.staff_number
        s = Staff.query.filter_by(staff_number=staff_number).first()
        # s.disable_reason = reason
        # s.account_state = u'用'
        s.account_state = 0
        s.save()
        sid = session['sid']
        name = session['name']
        f = Freeze.query.filter_by(number=staff_number). \
            order_by(Freeze.freeze_time.desc()).first()
        f.recovery_id = sid
        f.recovery_name = name
        f.recovery_time = datetime.datetime.now()
        db.session.add(f)
        db.session.commit()
        log(u'解冻账户:{}'.format(staff_number))
        return jsonify(dict(
            success=True,
            message=u'解冻成功！'
        ))
    return jsonify(dict(
        success=False,
        message=u'页面已过期，请刷新页面！'
    ))


@safe.route('/record/get_list')
def get_list():
    values = request.values
    print values
    limit = int(values.get('limit', '10'))
    offset = int(values.get('offset', '0'))
    list_type = request.values.get('list_type')
    number = values.get('number')
    start = values.get('start')
    end = values.get('end')
    name = values.get('name')
    operation = values.get('operation')
    search_type = values.get('search_type')
    tb_name = values.get('tb_name')  # 前端页面中多个表格共用同一组搜索参数，tb_name用于标识当前是哪一个表格在使用这些参数

    try:
        start = datetime.datetime.strptime(start, '%Y-%m-%d')
        end = datetime.datetime.strptime(end, '%Y-%m-%d')
        end = end + datetime.timedelta(days=1)  # 需要加一天才可以搜索到原本的end指定的日期
    except ValueError:
        return jsonify({'state': 1, 'msg': u'参数错误'})
    if list_type == "staff":
        model_log = StaffLog
        m_number = 'staff_number'

    elif list_type == "user":
        model_log = UserLog
        m_number = 'user_number'
    else:
        return jsonify({'state': -1})
    # ([('tb_name', u''), ('end', u'2017/03/17'), ('name', u''), ('area', u''), ('number', u''), ('search_type', u'5'),
    #   ('start', u'2017/03/17'), ('limit', u'50'), ('list_type', u'user'), ('offset', u'0'),
    #   ('_', u'1489718025981')]), ImmutableMultiDict([])])
    result = model_log.query

    if tb_name == list_type and search_type != '5':  # 5代表重置搜索，即不考虑搜索条件；tb_name用于检查当前的搜索参数是否与表格相对应
        if search_type == '0':
            g.kw[m_number] = number
        if search_type == '1' or search_type == '4':
            g.kw['name'] = name
        if search_type == '2' or search_type == '4':
            result = result.filter(model_log.operation.like('%' + operation + '%'))
        if search_type == '3' or search_type == '4':
            result = result.filter(model_log.time.between(start, end))

    data = []
    r = result.filter_by(**g.kw).order_by(model_log.time.desc()). \
        paginate(offset / limit + 1, limit, False)
    result = r.items
    count = r.total
    print list_type
    for item in result:
        if list_type == "staff":
            s = Staff.query.filter_by(staff_number=item.staff_number).first()
            role = s.role
            staff_number = session['staff_number']
            status = s.account_state  # 账户状态
            data.append({
                'id': item.id,
                'ip': item.ip,
                'staff_number': item.staff_number,
                'name': item.name,
                'operation': item.operation,
                'operation_time': item.time.strftime("%Y-%m-%d %H:%M"),
                'info': {'status': status,
                         'staff_number': staff_number,
                         'role': role}
            })
        else:
            s = User.query.filter_by(id=item.user_id).first()
            role = ''
            staff_number = ''
            status = s.account_state  # 账户状态
            data.append({
                'id': item.id,
                'ip': item.ip,
                'phone': item.phone,
                'staff_number': staff_number,
                'area': item.area,
                'name': item.name,
                'operation': item.operation,
                'operation_time': item.time.strftime("%Y-%m-%d %H:%M"),
                'info': {'status': status,
                         'staff_number': staff_number,
                         'role': role}
            })

    # if list_type == "staff":  # 内部账户
    #     query = StaffLog.query.order_by(StaffLog.time.desc()). \
    #         paginate(offset / limit + 1, limit, False)
    #     result = query.items
    #     count = query.total
    #
    #     for item in result:
    #         s = Staff.query.filter_by(staff_number=item.staff_number).first()
    #         status = s.account_state if s else ''
    #         data.append({
    #             'id': item.id,
    #             'ip': item.ip,
    #             'staff_number': item.staff_number,
    #             'name': item.name,
    #             'operation': item.operation,
    #             'operation_time': item.time.strftime("%Y-%m-%d %H:%M"),
    #             'freeze_status': status
    #         })
    # elif list_type == 'user':  # 外部账户
    #     result = UserLog.query.order_by(UserLog.time.desc()). \
    #         paginate(offset / limit + 1, limit, False).items
    #     count = UserLog.query.count()
    #
    #     for item in result:
    #         u = User.query.filter_by(user_number=item.user_id).first()
    #         status = u.account_state if u else ''
    #         data.append({
    #             'id': item.id,
    #             'ip': item.ip,
    #             'name': item.name,
    #             'phone': item.phone,
    #             'operation': item.operation,
    #             'operation_time': item.time.strftime("%Y-%m-%d %H:%M"),
    #             'area': item.area,
    #             'freeze_status': status
    #         })
    # else:
    #     return jsonify({'state': -1})
    json = {'total': count, 'rows': data}
    return jsonify(json)


@safe.route('/def_password', methods=['GET'])
def def_password():
    xfrs = random_string()
    xfrs_dict.update({xfrs: 0})
    def_pass = DefPassword.query.get(1)
    return render_template('safe/default_password.html',
                           def_pass=def_pass,
                           xfrs=xfrs)


@safe.route('/edit_password', methods=['POST'])
def edit_password():
    form = request.form
    xfrs = form.get('xfrs')
    password = form.get('password')
    if xfrs in xfrs_dict and password:
        xfrs_dict.pop(xfrs)
        p = DefPassword.query.get(1)
        if not p:
            p = DefPassword()
        p.default_password = password
        p.save()
        log(u'更新人员默认密码:{}'.format(password))
        flash(u'成功更新人员密码！')
        return redirect(url_for('.def_password'))
    else:
        flash(u'更改失败')
        return redirect(url_for('.def_password'))
